import { AuthService } from '@core/services/common/auth.service';
import { HttpHandler, HttpEvent, HttpEventType, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { Observable, tap, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { CODEMESSAGE } from '@app/config/constanst';
import { LoginInOutService } from '@core/services/common/login-in-out.service';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';

@Injectable()
export class ExpiredInterceptor implements HttpInterceptor {

  private refreshToking = false;

  constructor(
    private auth: AuthService,
    private loginInOutService: LoginInOutService,
    private router: Router,
    private message: NzMessageService,
  ) { }

  intercept(req: HttpRequest<NzSafeAny>, next: HttpHandler): Observable<HttpEvent<NzSafeAny>> {
    const newReq = req.clone();
    return next.handle(newReq).pipe(
      this.expiredHandle(newReq, next)
    );
  }

  expiredHandle(req: HttpRequest<NzSafeAny>, next: HttpHandler): NzSafeAny {
    console.log('expired-intercept-request');
    return switchMap((event: HttpResponse<NzSafeAny>): NzSafeAny => {
      if (event.type === HttpEventType.Response) {
        console.log('expired-intercept-response');
        const authToken: string = this.auth.getAuthorizationToken();
        //返回没有授权的处理
        if (event.body.code === 4010) {
          if (authToken) {
            this.message.error(CODEMESSAGE[event.body.code]);
            this.loginInOutService.logout();
            this.router.navigateByUrl('/login');
            return;
          }
        }
        if (event.body.code === 4030) {
          if (authToken) {
            this.message.error(CODEMESSAGE[event.body.code]);
          }
        }
      }
      return of(event);
    });
  }
}
